'use strict'

import { app, protocol, BrowserWindow, screen, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
let win
async function createWindow() {
  // Create the browser window.
  let screenWidth = (screen.getPrimaryDisplay().workAreaSize.width);
  win = new BrowserWindow({
    width: 300,
    height: 500,
    title: "喝水提醒",
    // alwaysOnTop: true,
    autoHideMenuBar: true,
    acceptFirstMouse: true,
    x: screenWidth - 100 - 300,
    y: 100,
    transparent: true,
    frame: false,
    resizable: false,
    webPreferences: {
      nodeIntegration: true,
      // devTools: false,
      enableRemoteModule: true,
      contextIsolation: false,
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}
let tray
async function createTray() {
  var { Menu, Tray, app, BrowserWindow } = require('electron');
  const path = require('path');
  let logo = 'logo.ico'
  if(process.platform == 'darwin'){
    logo = 'mac-logo.png'
  }
  tray = new Tray(path.join(__static, logo));
  const menu = Menu.buildFromTemplate([
    {
      label: '打开界面',
      click: () => {
        win.show()
      }
    },
    {
      label: '关于',
      click: function () {
        const winURL = process.env.NODE_ENV === 'development'
          ? `http://localhost:8080/`
          : "app://./index.html"
        let win1 = new BrowserWindow({
          width: 300,
          height: 180,
          title: "关于",
          // alwaysOnTop: true,
          autoHideMenuBar: true,
          acceptFirstMouse: true,
          resizable: false,
          webPreferences: {
            nodeIntegration: true,
            // devTools: false,
            enableRemoteModule: true,
            contextIsolation: false,
          }
        })
        win1.loadURL(winURL + '#/about')
      }
    },
    {
      label: '退出',
      click: function () {
        // BrowserWindow.getFocusedWindow().webContents().send('close-main-window');
        app.exit();
      }
    }
  ])
  tray.setToolTip('喝水提醒');
  tray.setContextMenu(menu);
  tray.on("double-click", () => {
    win.show()
  })
}


const getTheLock = app.requestSingleInstanceLock()

if (!getTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()
    }
  })

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })

  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.on('ready', async () => {
    // if (isDevelopment && !process.env.IS_TEST) {
    //   // Install Vue Devtools
    //   try {
    //     await installExtension(VUEJS_DEVTOOLS)
    //   } catch (e) {
    //     console.error('Vue Devtools failed to install:', e.toString())
    //   }
    // }
    createWindow()
    createTray()
  })

  // Exit cleanly on request from parent process in development mode.
  if (isDevelopment) {
    if (process.platform === 'win32') {
      process.on('message', (data) => {
        if (data === 'graceful-exit') {
          app.quit()
        }
      })
    } else {
      process.on('SIGTERM', () => {
        app.quit()
      })
    }
  }
  ipcMain.on('onClickAlert', (event, arg) => {
    win.webContents.send('onClickAlert', arg);
  })
  ipcMain.on('setStartWhenSystemStart', (event, arg) => {
    let needStart = arg
    console.log("设置开机自启：" + needStart)
    app.setLoginItemSettings({
      openAtLogin: needStart,
      openAsHidden: needStart,
      args: [
        '--hideWindow', '"' + needStart + '"'
      ]
    })
  })
  ipcMain.on('setTrayTips', (event, arg) => {
    if(arg == 'default'){
      tray.setToolTip("喝水提醒")
    }
    else{
      let {minute, second} = arg
      tray.setToolTip(`距离下次提醒还有:${minute}分${second}秒`)
    }
  })

}

